#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unordered_map>
#include "err.hpp"
#include "RingQueue.hpp"
#include "LockGuard.hpp"
#include "Thread.hpp"

namespace ns_server
{
    // using func_t = std::function<std::string(std::string)>;
    const static u_int16_t default_port = 8080;

    class UdpServer
    {
    public:
        UdpServer(u_int16_t port = default_port) : _port(port)
        {
            std::cout << "server addr: " << _port << std::endl;
            pthread_mutex_init(&_mutex, nullptr);

            _p = new Thread(1, std::bind(&UdpServer::recv, this));
            _c = new Thread(1, std::bind(&UdpServer::broadcast, this));
        }
        void start()
        {
            // 创建socket接口，打开网络文件
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success: " << _sock << std::endl;

            // 给服务器指明IP地址和端口号（Potr）
            struct sockaddr_in local;
            bzero(&local, sizeof(local));

            local.sin_family = AF_INET; // PF_INET
            local.sin_port = htons(_port);
            // inet_addr:
            // 将字符串风格的IP地址转化成为4字节int，"1.1.1.1" -> uint32_t
            // 然后将主机序列转化成为网络序列
            // local.sin_addr.s_addr = inet_addr(_ip.c_str());

            // 云服务器，或一款服务器，一般不要指明某一个确定的IP
            local.sin_addr.s_addr = INADDR_ANY; // 让我们的udp_server在启动的时候，bind本主机上的任意IP
            if (bind(_sock, (sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << _sock << std::endl;

            _p->run();
            _c->run();
        }

        void addUser(const std::string &name, const struct sockaddr_in &client)
        {
            //_online_user[name] = client;
            LockGuard lock(&_mutex);
            auto iter = _online_user.find(name);
            if (iter != _online_user.end())
            {
                return;
            }
            _online_user.insert(std::pair<const std::string, const struct sockaddr_in>(name, client));
        }

        void recv()
        {
            char buffer[1024];
            while (true)
            {
                // 收
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);
                if (n > 0)
                {
                    buffer[n] = '\0';
                }
                else
                {
                    continue;
                }

                // 提取客户端信息
                std::string clientip = inet_ntoa(client.sin_addr); // 注意把网络序列格式的32位整数转化成字符串形式
                uint16_t clientport = ntohs(client.sin_port);      // 注意把网络序列格式转化成主机格式
                std::cout << clientip << "-" << clientport << "# " << buffer << std::endl;

                // 构建一个用户并检查
                std::string name = clientip;
                name += '-';
                name += std::to_string(clientport);
                // 如果不存在就插入
                addUser(name, client);

                std::string message = name + ">> " + buffer;

                _rq.push(message);
                
                // //业务处理
                // std::string message = _service(buffer);

                // 发
                // sendto(_sock, message.c_str(), message.size(), 0, (struct sockaddr*)&client, sizeof(client));
            }
        }
        void broadcast()
        {
            while (true)
            {
                std::string sendstring;
                _rq.pop(&sendstring);

                std::vector<struct sockaddr_in> v;
                {
                    LockGuard lock(&_mutex);
                    for (auto user : _online_user)
                    {
                        v.push_back(user.second);
                    }
                }
                for (auto user : v)
                {
                    sendto(_sock, sendstring.c_str(), sendstring.size(), 0, (struct sockaddr *)&user, sizeof(user));
                }
            }
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&_mutex);
            _p->join();
            _c->join();

            delete _p;
            delete _c;
        }

    private:
        int _sock;
        u_int16_t _port;
        // func_t _service;
        std::unordered_map<std::string, struct sockaddr_in> _online_user; // 用于管理向本服务器发送信息的客户端用户
        pthread_mutex_t _mutex;
        RingQueue<std::string> _rq; // 用于存储用户所发送的信息
        Thread *_p;                 // 用于收（调用Recv）
        Thread *_c;                 // 用于发（调用Broadcast）
        // std::string _ip;
    };
}